import base64
import pickle

import django_redis


def merge_cart_cookie_to_redis(request, user, response):
    carts = request.COOKIES.get('carts')

    if not carts:
        return response
    carts = pickle.loads(base64.b64decode(carts))

    '''
    
    { 1:{count:1,selected:true}, }
    '''

    cart_dict = {}
    selected_list = []
    unselected_list = []

    for sku_id, cookie_dict in carts.items():
        cart_dict[sku_id] = cookie_dict['count']
        if cookie_dict['selected']:
            selected_list.append(sku_id)
        else:
            unselected_list.append(sku_id)

        # 获取 Redis 连接
        redis_client = django_redis.get_redis_connection('carts')
        pipeline = redis_client.pipeline()  # 创建一个 Redis pipeline


        pipeline.hset(f'{user.id}_carts',mapping=cart_dict)

        if selected_list:
            pipeline.sadd(f'{user.id}_selected', *selected_list)
        if unselected_list:
            pipeline.srem(f'{user.id}_selected', *unselected_list)

        pipeline.execute()

        response.delete_cookie('carts')

        return response
